package com.bite.blog.utils;

import com.bite.blog.enums.ResponseCodeEnum;
import com.bite.blog.enums.TokenPropEnum;
import com.bite.blog.model.Response;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {

    public static long validTime = 3 * 60 * 60 * 1000; // 3小时的有效期
    //密钥
    private static final String SECRET_STRING="CZ/SPsLUGkphMt7VsUyzQjHEU4rOud81mDlpiUAKerw=";
    //⽣成安全密钥
    private static final SecretKey KEY =
            Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_STRING));



    public static String getJwt(Map<String, Object> claims) {
        return Jwts.builder()
                .addClaims(claims)
                .signWith(KEY)
                .setExpiration(new Date(System.currentTimeMillis() + validTime))
                .compact();
    }

    void getKey() {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String secretString = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(secretString);
    }

    public static Claims parseJwt(String token) {
        Claims body = null;
        // 为什么要在这里抓取而不是在统一异常里捕获？ 因为后者是所有的 而token只有在这里有
        try {
            JwtParser build = Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build();
            body = build.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            // 登录过期
            log.warn("用户登录过期, ", e);
        } catch (SignatureException e) {
            log.error("输入错误的token, ", e);
        } catch (Exception e) {
            log.error("其他异常, ", e);
        }
        return body;
    }

    // 获取用户Id
    public static Integer getUserId(String token) {
        Integer id;
        if (token == null) {
            return null;
        }
        Claims claims = parseJwt(token);
        id = (Integer) claims.get(TokenPropEnum.USER_ID.getProp());
        return id;
    }
}
